package com.may.wind.config.web;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.SimpleTimeZone;

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
    /**
     * 注入配置文件数据
     * 时区
     */
    @Value("${spring.jackson.time-zone}")
    private String timeZone;

    /**
     * 注入配置文件的数据
     * 日期格式
     */
    @Value("${spring.jackson.date-format}")
    private String dateFormat;

    /**
     * 图片绝对地址与虚拟地址映射
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 文件磁盘图片url映射
        // 配置server虚拟路径，handler为前台访问的目录，locations为files相对应的本地路径
        registry.addResourceHandler("/api/file/img/**").addResourceLocations("file:E:/Project/Java/may/img/");
        // 默认访问static文件
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");

        // Spring Boot自动配置本身不会自动把/swagger-ui.html这个路径映射到对应的目录META-INF/resources/下面。需要动态的进行mvc资源文件的指定
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    /**
     * 定义时间格式转换器
     *
     * @return
     */
    @Bean
    public MappingJackson2HttpMessageConverter jackson2HttpMessageConverter() {
        //Json转换器
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        //对象映射器
        ObjectMapper mapper = new ObjectMapper();

        //配置映射规则
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setTimeZone(SimpleTimeZone.getTimeZone(timeZone));
        //设置时间戳格式
        mapper.setDateFormat(new SimpleDateFormat(dateFormat));
        //开启映射规则
        converter.setObjectMapper(mapper);
        return converter;
    }

    /**
     * 配置转换器
     *
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        //添加转换器
        converters.add(jackson2HttpMessageConverter());
    }
}
